#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
import logging.handlers
import os
import time

from config import settings

# 设置输出的等级
LEVELS = {
    'NOSET': logging.NOTSET,
    'DEBUG': logging.DEBUG,
    'INFO': logging.INFO,
    'WARNING': logging.WARNING,
    'ERROR': logging.ERROR,
    'CRITICAL': logging.CRITICAL
}


class LogHandler(object):
    def __init__(self, log_dir, filename):
        self.log_dir = log_dir
        self.filename = filename
        self.logger = logging.getLogger("")

        # 创建文件目录
        if not os.path.exists(self.log_dir):
            os.mkdir(self.log_dir)
        # 修改log保存位置
        timestamp = time.strftime("%Y-%m-%d", time.localtime())
        log_filename = f'{self.filename}.{timestamp}.log'
        log_filepath = os.path.join(settings.LOG_DIR, log_filename)
        rotatingFileHandler = logging.handlers.RotatingFileHandler(filename=log_filepath,
                                                                   maxBytes=1024 * 1024 * 50,
                                                                   backupCount=5)
        # 设置输出格式
        formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
        rotatingFileHandler.setFormatter(formatter)
        # 控制台句柄
        console = logging.StreamHandler()
        console.setLevel(logging.NOTSET)
        console.setFormatter(formatter)
        # 添加内容到日志句柄中
        self.logger.addHandler(rotatingFileHandler)
        self.logger.addHandler(console)
        self.logger.setLevel(logging.NOTSET)

    def info(self, message):
        self.logger.info(message)

    def debug(self, message):
        self.logger.debug(message)

    def warning(self, message):
        self.logger.warning(message)

    def error(self, message):
        self.logger.error(message)


app_logger = LogHandler(settings.LOG_DIR, 'lotto-ai')
app_err_logger = LogHandler(settings.LOG_DIR, 'lotto-ai.err')
app_warn_logger = LogHandler(settings.LOG_DIR, 'lotto-ai.warn')


# if __name__ == '__main__':
#     logger = LogHandler(settings.LOG_DIR, 'lotto-ai')
#     logger.info("test")
